import { TreeType } from "../type"
import { useStore } from "@/store/index"
import { ref, onMounted, nextTick, watch, Ref } from "vue"

function useState() {
  const store = useStore()
  const treeProps: any = {
    label: "name",
    children: "children",
    isLeaf: "isDir",
    disabled: "disable",
  }
  const filterText = ref("")
  const treeRef = ref<TreeType>() as Ref<TreeType>

  const treeHoverId = ref<null | number>(null)

  onMounted(async () => {
    await store.dispatch("fileTree/getFile")
    nextTick(() => {
      expandTree()
    })
  })
  // 监听输入框文本变化进行搜索
  watch(
    () => filterText.value,
    () => {
      treeRef.value?.filter(filterText.value)
    }
  )
  // 获取文件树数据
  watch(
    () => store.state.fileTree.data,
    () => {
      nextTick(() => {
        getExpandedList()
        expandTree()
        setCurrentNode()
      })
    }
  )

  // 获取树展开项的列表
  const getExpandedList = () => {
    const expandeArr = []
    for (const i in treeRef.value?.store.nodesMap) {
      if (treeRef.value?.store.nodesMap[i].expanded) {
        expandeArr.push(i)
      }
    }
    store.commit("fileTree/changeTreeExpandedArr", expandeArr)
  }

  // 展开缓存的树节点
  const expandTree = () => {
    store.state.fileTree.treeExpandedArr.forEach((item) => {
      ;(treeRef.value as TreeType).store.nodesMap[item].expanded = true
    })
  }

  // 指定当前缓存的markdown
  const setCurrentNode = () => {
    if (store.state.markdown.id) {
      treeRef.value?.setCurrentKey(store.state.markdown.id)
    }
  }

  return {
    treeProps,
    treeRef,
    filterText,
    treeHoverId,
    getExpandedList,
    expandTree,
  }
}
export default useState
